﻿using CRM_Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace CRM_Web.Controllers
{
    public class UsersController : ApiController
    {
        // GET: api/Users
        [HttpGet]
        public IHttpActionResult users(int page, int limit, string LoginName, string Islockout)
        {
            using (CRMDBEntities db = new CRMDBEntities())
            {
                var tablelist = db.Users.AsEnumerable();
                if (!String.IsNullOrEmpty(LoginName))
                {
                    tablelist = tablelist.Where(p => p.LoginName.Contains(LoginName));
                }
                if (!String.IsNullOrEmpty(Islockout))
                {
                    tablelist = tablelist.Where(p => p.Islockout == Convert.ToInt32(Islockout));
                }
                var list = tablelist.Select(p => new
                {
                    Id = p.Id,
                    LoginName = p.LoginName,
                    Islockout = p.Islockout,
                    LookTime = p.LookTime,
                    ProtectEMail = p.ProtectEMail,
                    protectMTel = p.protectMTel,
                    CreateTime = p.CreateTime
                }).ToList();
                int count = list.Count();
                return Json(new
                {
                    count = count,
                    data = list.OrderByDescending(p => p.Id).Skip((page - 1) * limit).Take(limit).ToList()
                });
            }
        }
        /// <summary>
        /// 添加员工管理
        /// </summary>
        /// <param name="add"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult addUsers([FromBody]Users add)
        {
            using (CRMDBEntities db = new CRMDBEntities())
            {
                var username = db.Users.FirstOrDefault(p => p.LoginName == add.LoginName);
                if (username != null)
                {
                    return Json(new { code = -1, msg = "此用户名已存在，请重新输入用户名！" });
                }
                else
                {
                    add.Islockout = 0;
                    add.CreateTime = DateTime.Now;
                    add.LookTime = DateTime.Now;
                    db.Users.Add(add);
                    int n = db.SaveChanges();
                    if (n > 0)
                    {
                        return Json(new { code = 0, msg = "添加成功！" });
                    }
                    else
                    {
                        return Json(new { code = -1, msg = "添加失败！" });
                    }
                }
            }
        }
        /// <summary>
        /// 删除员工处理
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult DelUser([FromBody] deluser userid)
        {
            using (CRMDBEntities db = new CRMDBEntities())
            {
                //1.判断是否为当前用户
                var a1 = db.Users.FirstOrDefault(p => p.Id == userid.Id);
                if (a1.Id != userid.userId)
                {
                    //2.判断此用户下是否存在角色
                    var a2 = db.UserRoles.SingleOrDefault(p => p.UserId == a1.Id);
                    if (a2 != null)
                    {
                        return Json(new { code = -1, msg = "此用户已分配角色，不能进行删除操作！" });
                    }
                    else
                    {
                        db.Users.Remove(a1);
                        int n = db.SaveChanges();
                        if (n > 0)
                        {
                            return Json(new { code = 0, msg = "删除成功！" });
                        }
                        else
                        {
                            return Json(new { code = -1, msg = "删除失败！" });
                        }
                    }
                }
                else
                {
                    return Json(new { code = -1, msg = "此用户为当前登录用户，不能删除！" });
                }
                  
            }
        }
        /// <summary>
        /// 编辑员工信息处理
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult editUser([FromBody] Users bb)
        {
            using(CRMDBEntities db=new CRMDBEntities())
            {
                var b = db.Users.SingleOrDefault(p => p.Id == bb.Id);
                b.LoginName = bb.LoginName;
                b.ProtectEMail = bb.ProtectEMail;
                b.protectMTel = bb.protectMTel;
                b.Islockout = bb.Islockout;
                int n = db.SaveChanges();
                if (n > 0)
                {
                    return Json(new { code = 0, msg = "编辑成功！" });
                }
                else
                {
                    return Json(new { code = -1, msg = "编辑失败！" });
                }
            }
        }
        /// <summary>
        /// 重置处理
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult resetUser([FromBody] Users dd)
        {
            using(CRMDBEntities db=new CRMDBEntities())
            {
                var ddd = db.Users.FirstOrDefault(p => p.Id == dd.Id);
                if (ddd != null)
                {
                    if (ddd.Password == "123456")
                    {
                        return Json(new { code = -1, msg = "原密码已是123456，无需重置操作！" });
                    }
                    else
                    {
                        ddd.Password = Convert.ToString(123456);
                        int n = db.SaveChanges();
                        if (n > 0)
                        {
                            return Json(new { code = 0, msg = "重置成功！" });
                        }
                        else
                        {
                            return Json(new { code = -1, msg = "重置失败！" });
                        }
                    }     
                }
                else
                {
                    return Json(new { code = -1, msg = "重置密码用户不存在！" });
                }
            }
        }
        /// <summary>
        /// 状态按钮
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult Idlockout([FromBody] Users ff)
        {
            using(CRMDBEntities db=new CRMDBEntities())
            {
                var list = db.Users.FirstOrDefault(p => p.Id == ff.Id);
                if (list.Islockout == 0)
                {
                    list.Islockout = 1;
                    list.LookTime = null;
                    int m = db.SaveChanges();
                    if (m > 0)
                    {
                        return Json(new { code = 0, msg = "锁定成功！" });
                    }
                    else
                    {
                        return Json(new { code = -1, msg = "锁定失败！" });
                    }
                }
                else
                {
                    list.Islockout = 0;
                    list.LookTime = DateTime.Now;
                    int n = db.SaveChanges();
                    if (n > 0)
                    {
                        return Json(new { code = 0, msg = "解除锁定成功！" });
                    }
                    else
                    {
                        return Json(new { code = -1, msg = "解除锁定失败！" });
                    }
                }         
            }
        }
        /// <summary>
        /// 获取穿梭框数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetRoles(int Id)
        {
            using (CRMDBEntities db = new CRMDBEntities())
            {
                var list = db.UserRoles.Where(t => t.UserId == Id).ToList();
                var Roleslist = db.Roles.Select(t => new { key = t.Id, label = t.Name }).ToList();
                if (list.Count > 0)
                {
                    var ss = "";
                    foreach (var item in list)
                    {
                        ss += Convert.ToString(item.RoleId) + ",";
                    }

                    ss = ss.Substring(0, ss.Length - 1);
                    var mo = ss.Split(',').Select(x => int.Parse(x)).ToList();

                    return Json(new { code = 0, data = Roleslist, valus = mo, userId = Id });
                }
                else
                {
                    return Json(new { code = -1, data = Roleslist, valus = "", userId = Id });
                }

            }
        }
        [HttpGet]
        public IHttpActionResult GetUsersRolesAdd(int userId, string movedKey)
        {
            using (CRMDBEntities db = new CRMDBEntities())
            {
                var mo = movedKey.Split(',').Select(x => int.Parse(x)).ToList();
                for (int i = 0; i < mo.Count; i++)
                {
                    UserRoles ur = new UserRoles() { UserId = userId, RoleId = mo[i] };
                    db.UserRoles.Add(ur);
                }
                //char[] ss = movedKeys.ToCharArray();
                //foreach (var item in ss)
                //{
                //    UserRoles ur = new UserRoles() { UserId = UserId, RoleId = item };
                //    db.UserRoles.Add(ur);
                //}

                int n = db.SaveChanges();
                if (n > 0)
                {
                    return Json(new { code = 0, msg = "添加成功" });
                }
                else
                {
                    return Json(new { code = -1, msg = "添加失败" });
                }
            }
        }
        [HttpGet]
        public IHttpActionResult GetUsersRolesDel(int userId, string movedKey)
        {
            using (CRMDBEntities db = new CRMDBEntities())
            {
                var mo = movedKey.Split(',').Select(x => int.Parse(x)).ToList();
                //for (int i = 0; i < mo.Count; i++)
                //{
                //    var ss = db.UserRoles.FirstOrDefault(t => t.RoleId == mo[i]&&t.UserId==userId);
                //    db.UserRoles.Remove(ss);
                //}
                foreach (var item in mo)
                {
                    var ss = db.UserRoles.FirstOrDefault(t => t.RoleId == item && t.UserId == userId);
                    db.UserRoles.Remove(ss);
                }
                //char[] ss = movedKeys.ToCharArray();
                //foreach (var item in ss)
                //{
                //    UserRoles ur = new UserRoles() { UserId = UserId, RoleId = item };
                //    db.UserRoles.Add(ur);
                //}

                int n = db.SaveChanges();
                if (n > 0)
                {
                    return Json(new { code = 0, msg = "删除成功" });
                }
                else
                {
                    return Json(new { code = -1, msg = "删除失败" });
                }
            }
        }



    }
}
